package com.yuerenjf.yuerenjinfu.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qiniu.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.adapter.FirstEvent;
import com.yuerenjf.yuerenjinfu.bean.LoginBean;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.CommonUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;
import com.yuerenjf.yuerenjinfu.utils.ImageUtils;
import com.yuerenjf.yuerenjinfu.widget.SFProgrssDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    public final static String FROM_TYPE_MAIN_TAB="1";
    public final static String FROM_TYPE_MAIN_TAB_OWN="3";
    private TextView tv_reg;
    private AutoCompleteTextView et_login_username;
    private EditText et_login_pwd;
    private TextView tv_login;
    private LoginBean loginBean;
    private TextView tv_forget_password;

    private String url;
    private String fromType;

    private ImageView codeImage;
    private EditText codeImageEdit;
    private LinearLayout codeImageLayout;
    public static void launchLoginActivity(Context context,String fromType) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("fromType",fromType);
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fromType=getIntent().getStringExtra("fromType");
        tv_title.setText("登录");

        ll_back.setOnClickListener(this);

        url = getIntent().getStringExtra("url");
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Override
    protected View getChildView() {
        View view = View.inflate(this, R.layout.activity_login, null);
        tv_reg = (TextView) view.findViewById(R.id.tv_reg);
        et_login_username = (AutoCompleteTextView) view.findViewById(R.id.et_login_username);
        et_login_pwd = (EditText) view.findViewById(R.id.et_login_pwd);
        tv_login = (TextView) view.findViewById(R.id.tv_login);
        tv_forget_password = (TextView) view.findViewById(R.id.tv_forget_password);
        codeImage=(ImageView)view.findViewById(R.id.tv_register_code_image);
        codeImageEdit= (EditText) view.findViewById(R.id.et_register_code_number_edit);
        codeImageLayout= (LinearLayout) view.findViewById(R.id.rl_login_code_number_layout);
        tv_reg.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);
        codeImage.setOnClickListener(this);


        String userName = CacheUtils.getString(this, ConstantUtils.SP_USER_NAME);
        if (!userName.equals("")) {
            String[] userNameArr = userName.split(",");
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, userNameArr);
            et_login_username.setAdapter(adapter);
            et_login_username.setThreshold(1);
        }
        return view;
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_reg:
                startActivity(new Intent(this, RegisterActivity.class));
//                MainActivity mainActivity= (MainActivity)LoginActivity.this;
//                mainActivity.switchContent(mainActivity.getmCurrentFragment(),new RegisterFragment(),"register");
                break;
            case R.id.tv_login:
                if (!CommonUtils.isMobileNO(et_login_username.getText().toString())) {
                    Toast.makeText(LoginActivity.this, "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(et_login_pwd.getText().toString())) {
                    Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (codeImageLayout.getVisibility()==View.VISIBLE&&TextUtils.isEmpty(codeImageEdit.getText().toString())) {
                    Toast.makeText(LoginActivity.this, "请输入右侧图片的数字", Toast.LENGTH_SHORT).show();
                    return;
                }

                getLoginData(et_login_username.getText().toString(), et_login_pwd.getText().toString());
                break;
            case R.id.tv_forget_password:
//                MainActivity mainActivity2= (MainActivity)LoginActivity.this;
//                Log.i("mainActivity",mainActivity2.toString());
//                mainActivity2.switchContent(mainActivity2.getmCurrentFragment(),new RetrieveFragment(),"Retrieve");
                startActivity(new Intent(this, RetrieveActivity.class));
                break;
            case R.id.ll_back:
                finish();
                break;

            case R.id.tv_register_code_image:
                getCodeImage();
                break;
        }
    }


    public void getLoginData(final String phone, String pwd) {
        final SFProgrssDialog dialog = SFProgrssDialog.show(LoginActivity.this, "");
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", pwd);
        map.put("imagecode", codeImageEdit.getText().toString());
        Xutils.getInstance().post(LoginActivity.this, Constants.URL_LOGIN, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    String message = jsonObject.getString("message");
                    if (status == 200) {
                        loginBean = new Gson().fromJson(result, LoginBean.class);
                        String uid = loginBean.getData().getUid();
                        String keep_code = loginBean.getData().getKeep_code();
                        String secret = loginBean.getData().getSecret();
//                        String token = CacheUtils.getString(LoginActivity.this, ConstantUtils.SP_TOKEN);
                        String web_signature = CommonUtils.md5(CommonUtils.md5(CacheUtils.getString(LoginActivity.this, ConstantUtils.SP_TOKEN) + uid) + secret);
//
                        String signature = CommonUtils.md5(CommonUtils.md5(CacheUtils.getString(LoginActivity.this, ConstantUtils.SP_TOKEN) + uid) + secret);

                        String avatar=loginBean.getData().getAvatar();
                        if(!StringUtils.isNullOrEmpty(avatar)){
                            CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_AVATAR, loginBean.getData().getAvatar());
                        }
                        CacheUtils.setLong(LoginActivity.this, ConstantUtils.SP_SIGNATURE_TIME, System.currentTimeMillis());
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_USER_PHONE, phone);
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_UID, uid);
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_SECRET, secret);
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_KEEP_CODE, keep_code);
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_WEB_SIGNATURE, web_signature);
                        CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_SIGNATURE, signature);
                        saveUserName();
                        if(fromType.equals(FROM_TYPE_MAIN_TAB)){
                            Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }else if(fromType.equals(FROM_TYPE_MAIN_TAB_OWN)){
                            Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("current","3");
                            startActivity(intent);
                        }else if(fromType.contains("http")){
                            WebActivity.launchActivity(LoginActivity.this,fromType);
                            finish();
                        }
                    } else if(status==300){
                        Toast.makeText(LoginActivity.this,message,Toast.LENGTH_LONG).show();
                        codeImageLayout.setVisibility(View.VISIBLE);
                        codeImageEdit.setText("");
                        JSONObject object = jsonObject.getJSONObject("data");
                        String base64Code= object.getString("img");
                        Bitmap bp= ImageUtils.stringtoBitmap(base64Code);
                        codeImage.setImageBitmap(bp);
                        codeImageEdit.setText("");
                    }else{
                        Toast.makeText(LoginActivity.this,message,Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });


    }

    private void saveUserName() {
        String sUserName = CacheUtils.getString(LoginActivity.this, ConstantUtils.SP_USER_NAME);
        if (!sUserName.contains(",")) {
            sUserName = "";
        }
        if (!sUserName.contains(et_login_username.getText().toString())) {
            CacheUtils.setString(LoginActivity.this, ConstantUtils.SP_USER_NAME, sUserName + et_login_username.getText().toString() + ",");
        }
    }


    private void getCodeImage() {
        Map<String, String> map = new HashMap<>();
        map.put("type","1");
        Xutils.getInstance().get(LoginActivity.this, Constants.URL_REGISTER_AUTH_CODE, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    String message = jsonObject.getString("message");
                    if (status == 200) {
                        JSONObject object = jsonObject.getJSONObject("data");
                        String base64Code= object.getString("img");
                        Bitmap bp= ImageUtils.stringtoBitmap(base64Code);
                        codeImage.setImageBitmap(bp);
                    } else if (status == 300) {
                        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {

            }
        });


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FirstEvent event) {
        String msg = "onEventMainThread收到了消息：" + event.getMsg();
        LogUtil.i(msg);
        if(event.getMsg()!=null){
            finish();
        }

    }
}
